package ru.hh.school;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import static ru.hh.school.Util.*;

/**
 * Открывает консоль с чатом, в котором отображаются сообщения приходящие пользователю с ChatServer,
 * а также ожидает соединения с ClientInputConsole.
 * После получения соединения, пробрасывает ввод с ClientInputConsole на ChatServer.
 */
public class ClientChatConsole {
    private final static int chatServerPort = 12345;
    public static final String GREETINGS = "    //    / / //    / /       //   ) )  //    / / // | |  /__  ___/ \n" +
                                           "   //___ / / //___ / /       //        //___ / / //__| |    / /     \n" +
                                           "  / ___   / / ___   /       //        / ___   / / ___  |   / /      \n" +
                                           " //    / / //    / /       //        //    / / //    | |  / /       \n" +
                                           "//    / / //    / /       ((____/ / //    / / //     | | / /        \n" +
                                           "Hello! Please introduce yourself - print /nick <your name>.\n" +
                                           "Use /help command to view list of available commands.";

    public static void main(String[] args) {

        final int port = readPortFromAppArgs(args);
        String chatServerHostName = readServerHostnameFromAppArgs(args);
        if (port == -1) return;
        if (chatServerHostName == null) {
            chatServerHostName = "localhost";
        }

        Socket clientEndpoint = null;
        ServerSocket localServerSocket = null;
        Socket localSocket = null;
        ClientInputHandler clientInputHandler = null;
        ObjectInputStream chatServerInputStream = null;
        try {
            clientEndpoint = new Socket(chatServerHostName, chatServerPort);
            localServerSocket = new ServerSocket(port);
            // wait for ClientInputConsole connection
            localSocket = localServerSocket.accept();
            clientInputHandler = new ClientInputHandler(clientEndpoint.getOutputStream(), localSocket.getInputStream(), Thread.currentThread());
            clientInputHandler.start();
            chatServerInputStream = new ObjectInputStream(clientEndpoint.getInputStream());
            System.out.println(GREETINGS);
            while (true) {
                System.out.println(chatServerInputStream.readObject());
            }
        }
        catch (Exception e) {
            // Ignore
        }
        finally {
           if (clientInputHandler != null) {
                clientInputHandler.interrupt();
            }
         
            if (chatServerInputStream != null) {
                try {
                    chatServerInputStream.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
            if (localSocket != null) {
                try {
                    localSocket.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
            if (localServerSocket != null) {
                try {
                    localServerSocket.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
            if (clientEndpoint != null) {
                try {
                    clientEndpoint.close();
                } catch (IOException e1) {
                    // Ignore  
                }
            }

        }
    }
}
